console.log("This is content.js")
const ImgContainerId = 'DiImageContainerId'

function showImgs() {
    let container = document.getElementById(ImgContainerId)
    if (container != null) {
        container.parentElement.removeChild(container)
    }

    container = document.createElement('div')
    container.setAttribute('id', ImgContainerId)
    document.getElementsByTagName('body')[0].appendChild(container)

    const imgList = document.getElementsByTagName('img')
    let imgSrcList = []
    for (let idx = 0; idx < imgList.length; idx++) {
        const tmpImg = imgList[idx]
        console.log(`Img info: ${tmpImg.width} x ${tmpImg.height}; ${tmpImg.src}`)
        if (tmpImg.width != null
            && tmpImg.height != null
            && tmpImg.width >= 250
            && tmpImg.height >= 100
            && tmpImg.src != null
            && (tmpImg.src + '').length > 10) {
            imgSrcList.push({
                width: tmpImg.width,
                height: tmpImg.height,
                src: tmpImg.src + ''
            })
        }
    }

    // 排序生成图片
    const sortedList = imgSrcList.sort((a, b) => {
        if (a.width === b.width) {
            return a.height - b.height;
        }
        return a.width - b.width
    })
    const timerId = setTimeout(() => {
        for (let idx = sortedList.length - 1; idx >= 0; idx--) {
            const imgUrl = sortedList[idx].src

            const itemContainer = document.createElement('div')
            itemContainer.className = 'di-item-container'

            const tmpImgTag = document.createElement('img')
            tmpImgTag.setAttribute('src', imgUrl)
            itemContainer.appendChild(tmpImgTag)

            const downloadBtn = document.createElement('a')
            downloadBtn.setAttribute('href', `DiImageDownloader://index?img=${encodeURI(imgUrl)}`)
            downloadBtn.classList = ['di-download-btn']
            downloadBtn.style.color = "#009966"
            downloadBtn.innerText = '设置为桌面壁纸'
            itemContainer.appendChild(downloadBtn)

            container.appendChild(itemContainer)
        }

        // 关闭按钮
        const closeBtn = document.createElement('button')
        closeBtn.innerText = 'x'
        closeBtn.className = 'di-close-btn'
        container.appendChild(closeBtn)
        closeBtn.addEventListener("click", () => {
            const app = document.getElementById(ImgContainerId)
            if (app != null) {
                app.parentElement.removeChild(app)
            }
        })
        clearTimeout(timerId)
    }, 500);
}



chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    // console.log(sender.tab ?"from a content script:" + sender.tab.url :"from the extension");
    if (request === 'MsgShowImages') {
        showImgs()
        sendResponse('OK')
    }
});
